package com.hqbzl.c1.pool;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Array;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerArray;

@Slf4j
public class TestPool {
    public static void main(String[] args) {
        final Pool pool = new Pool(2);

        final List<Connection> connections = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final Thread thread = new Thread(() -> {
                final Connection conn = pool.borror();
                connections.add(conn);
                log.debug("{}={}", Thread.currentThread().getName(), conn);
                pool.completed(conn);
            }, "th-" + i);
            thread.start();
        }
    }


    static class Pool {
        private int size;
        AtomicIntegerArray status;
        Connection[] connections;

        public Connection borror() {
            while (true) {
                for (int i = 0; i < size; i++) {
                    if (status.get(i) == 0) {
                        if (status.compareAndSet(i, 0, 1)) {
                            return connections[i];
                        }
                    }
                }
                synchronized (this) {
                    try {
                        log.debug("wait");
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }


        }

        public Pool(int size) {
            this.size = size;
            status = new AtomicIntegerArray(size);
            connections = new Connection[size];
            for (int i = 0; i < size; i++) {
                status.set(i, 0);
                connections[i] = new Connection();
            }
        }

        public void completed(Connection conn) {
            for (int i = 0; i < size; i++) {
                if (connections[i] == conn) {
                    status.set(i, 0);
                    synchronized (this) {
                        log.debug("{} completed", Thread.currentThread().getName());
                        this.notify();
//                        this.notifyAll();
                    }
                }
            }
        }
    }

    static class Connection {

    }
}
